/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package oggetti;


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import database.DB;
import it.jack.HeaderFooter;

import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;

/**
 *
 * @author turchijacopo
 */
public class PDF {
	
    public static String write(DestinatarioDT destinatario, ArrayList<Riparazione> listaRiparazioni) {
        JFileChooser cs = new JFileChooser();
        if (cs.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            String filename = cs.getSelectedFile().getAbsolutePath() + ".pdf";
            try {
                writePDF(filename, destinatario.toString(), listaRiparazioni);
                return filename;
            } catch (FileNotFoundException ex) {
                Logger.getLogger(PDF.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            } catch (DocumentException ex) {
                Logger.getLogger(PDF.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            } catch (MalformedURLException ex) {
                Logger.getLogger(PDF.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            } catch (IOException ex) {
                Logger.getLogger(PDF.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }
        }else
        	return null;
    }

    public static void creaHeader(PdfPTable table, String data, int numpag,int idScheda) {
    	
    	table.setWidthPercentage(100);
        ParagrafoHeader head[] = new ParagrafoHeader[4];
        String headString[] = new String[]{"N.DOCUMENTO","DATA","PAGINA","DOCUMENTO DI TRASPORTO\n(D.P.R. 472/96 DEL 14/08/96)"};
        for(int i=0;i<head.length;i++){
           head[i] = new ParagrafoHeader(headString[i]);
        }
    	PdfPCell cella = new PdfPCell(head[0]);
        cella.setFixedHeight(20);
        table.addCell(cella);
        table.addCell(new PdfPCell(head[1]));
        table.addCell(new PdfPCell(head[2]));
        PdfPCell cell = new PdfPCell(head[3]);
        cell.setRowspan(2);
        table.addCell(cell);
        
        Paragraph scheda = new Paragraph("" + idScheda);
        scheda.setAlignment(1);
        table.addCell(new PdfPCell(scheda));
        table.addCell(new PdfPCell(new Paragraph(data)));
        scheda = new Paragraph("1");
        scheda.setAlignment(1);
        table.addCell(new PdfPCell(scheda));
        scheda = new Paragraph("");
        scheda.setAlignment(1);
        table.addCell(new PdfPCell(scheda));
        scheda.setAlignment(1);
    }
    
    public static void creaFooter(PdfPTable table1, PdfPTable table2) {
    	
        table1.setWidthPercentage(100);
        table1.addCell(new PdfPCell(new ParagrafoHeader("ANNOTAZIONI")));
        table1.addCell(new PdfPCell(new ParagrafoHeader("TOTALE DOCUMENTO")));
        table1.addCell(new PdfPCell(new Paragraph("")));
        table1.addCell(new PdfPCell(new Paragraph("0.00")));
        
        table2.setWidthPercentage(100);
        table2.addCell(new PdfPCell(new ParagrafoHeader("INCARICATO DEL TRASPORTO")));
        table2.addCell(new PdfPCell(new ParagrafoHeader("FIRMA E TIMBRO PER MERCE RICEVUTA")));
        table2.addCell(new PdfPCell(new Paragraph("")));
        PdfPCell cella4 = new PdfPCell(new Paragraph(""));
        cella4.setFixedHeight(30);
        table2.addCell(cella4);
    }
    

    private static void fillTableWithRiparazioni(ArrayList<Riparazione> lista, PdfPTable table3) {
        table3.addCell(new PdfPCell(new ParagrafoHeader("QNT.")));
        table3.addCell(new PdfPCell(new ParagrafoHeader("DESCRIZIONE DEI  BENI (NATURA E QUALITA')")));
        table3.addCell(new PdfPCell(new ParagrafoHeader("IMP. U.")));
        table3.addCell(new PdfPCell(new ParagrafoHeader("RIF. ORD. CLIENTE")));
        int blank = 0;
        
        if(lista.size()<=6)
           blank = 6-lista.size();
            
        
        for(int i=0;i<lista.size();i++){
            PdfPCell cella5 = new PdfPCell(new Paragraph(""+(i+1)));
            cella5.setMinimumHeight(30);
            table3.addCell(cella5);
            table3.addCell(new PdfPCell(new Paragraph(lista.get(i).getDescrizione())));
            table3.addCell(new PdfPCell(new Paragraph("0.0")));
            table3.addCell(new PdfPCell(new Paragraph(lista.get(i).getIdCliente())));
        }
        blank = (blank*4)+(blank*2)-2;
        for(int i=0;i<blank;i++){
           table3.addCell(new PdfPCell(new Paragraph(" ")));
        }
    }
    
    public static void writePDFAccettazione(Cliente c,Riparazione r) throws FileNotFoundException, DocumentException, BadElementException, MalformedURLException, IOException {
    	Document document = new Document(PageSize.A4, 10, 10, 10, 10);
    	 PdfWriter writer= PdfWriter.getInstance(document,new FileOutputStream(new File("accettazionetmp.pdf")));
    	 document.open();
    	 // prima riga
    	 PdfPTable table1 = new PdfPTable(new float[]{1f, 1f,1f,5f});
         table1.setWidthPercentage(100);
         PdfPCell c1=new PdfPCell(new Paragraph("Dati Cliente"));
         PdfPCell c2=new PdfPCell(new Paragraph("SK. N."));
         PdfPCell c3=new PdfPCell(new Paragraph(""+c.getId()));
         PdfPCell c4=new PdfPCell(new Paragraph("RIF. CLIENTE: "+c.getNome()+" "+c.getCognome()));
         c1.setBorder(0);
         c2.setBorder(0);
         c3.setBorder(0);
         c4.setBorder(0);
         table1.addCell(c1);
         table1.addCell(c2);
         table1.addCell(c3);
         table1.addCell(c4);
         //prima tabella
         PdfPTable table2 = new PdfPTable(new float[]{1f, 1f,1f,1f});
         table2.setWidthPercentage(100);
         table2.addCell(new PdfPCell(new Paragraph("Spett.")));
         table2.addCell(new PdfPCell(new Paragraph(" "+c.getCognome()+" "+c.getNome())));
         table2.addCell(new PdfPCell(new Paragraph("SK.N.")));
         table2.addCell(new PdfPCell(new Paragraph(" "+c.getId())));
         table2.addCell(new PdfPCell(new Paragraph("Via:")));
         table2.addCell(new PdfPCell(new Paragraph(" "+c.getResidenza())));
         table2.addCell(new PdfPCell(new Paragraph("Telefono:")));
         table2.addCell(new PdfPCell(new Paragraph(" "+c.getTelefono())));
         Paragraph p=new Paragraph("\n");
         Paragraph p2=new Paragraph("Dati apparato");
         Paragraph p3=new Paragraph("GARANZIA: FUORI GARANZIA");
         //tabella dati apparato
         PdfPTable table3 = new PdfPTable(new float[]{1f, 1f,1f});
         table3.setWidthPercentage(100);
         table3.addCell(new PdfPCell(new Paragraph("ID SCHEDA "+r.getScheda())));
         table3.addCell(new PdfPCell(new Paragraph("IMEI: "+r.getImei())));
         table3.addCell(new PdfPCell(new Paragraph("PREVENTIVO : "+r.getPreventivo())));
         table3.addCell(new PdfPCell(new Paragraph("NOTE RIPARAZIONE: "+r.getNote())));
         table3.addCell(new PdfPCell(new Paragraph("DIFETTI DENUNCIATI: "+r.getDifetto())));
         table3.addCell(new PdfPCell(new Paragraph("DATA RIPARAZIONE: "+r.getDataConsegna())));
         p3.setAlignment(2);
         
         String voceParagrafo="Per le riparazioni eseguite fuori garanzia, la stessa viene garantita per"+
         " 90 giorni dalla data di riparazione, per i difetti riscontrati ed i ricambi sostituiti.\nNon "+
         "vengono garantite le sostituzioni dei connettori di carica, e le riparazioni su apparati ossidati."+
         "\nSi precisa che eventuali riparazioni gestite come rientro non prolungano la garanzia, pertanto "+
         "il termine di scadenza fa riferimento al primo intervento.";
         Paragraph p4= new Paragraph(voceParagrafo);
         
         document.add(table1);
         document.add(table2);
         document.add(p);
         document.add(p);
         document.add(p2);
         document.add(p);
         document.add(table3);
         document.add(p3);
         document.add(p);
         document.add(p);
         document.add(p4);
         document.newPage();
         // seconda pagina
         
         String condizione="Lorem ipsum dolor sit amet, consectetur adipiscing elit. In vitae mauris diam"+
         ", at condimentum est. Phasellus id purus justo. Nullam a lacus sed massa viverra congue. Cras"+
         " mattis velit nec nulla consectetur in gravida est dignissim. In vitae hendrerit turpis. Nam"+
         " justo ante, ultrices at feugiat non, sodales a dolor. Sed luctus mollis eros, at volutpat "+
         "sapien fringilla id. Quisque nec quam non turpis vulputate varius. Morbi sit amet quam vitae"+
         " libero sodales cursus et sagittis est."+
         "Phasellus placerat rhoncus mauris et faucibus. Donec convallis quam semper arcu eleifend"+
         " malesuada. Quisque orci enim, dignissim sit amet ullamcorper eu, mollis nec odio. Quisque "+
         "sollicitudin vehicula quam in tempor. Cras imperdiet mauris eget massa aliquet nec malesuada "+
         "justo luctus. Vestibulum in leo erat, quis ornare dui. Aenean non ante ante, at accumsan purus.";
        
         Paragraph p5= new Paragraph("CONDIZIONI PER L'ESECUZIONE DELLA RIPARAZIONE");
         p5.setAlignment(1);
         Paragraph p6= new Paragraph(condizione);
         Paragraph p7= new Paragraph("Firma del cliente .......................................");
         String legge="Ai sensi della legge 675/96 art.10 e 13 sulla tutela dei dati personali, il cliente"+
         "acconsente all'assunzione ed al trattamento dei dati personali";
         Paragraph p8= new Paragraph(legge);
         
         com.itextpdf.text.Image img= com.itextpdf.text.Image.getInstance("images/logo.png");
		 img.scalePercent(70);
		 img.setAlignment(1);
		 
		 String attenzione="ATTENZIONE!\nPER RIPARARE IL CELLULARE SARANNO CANCELLATI DATI, RUBRICA,FOTO";
		 Paragraph p9=new Paragraph(attenzione);
		 PdfPTable table4 = new PdfPTable(new float[]{1f});
		 p9.setAlignment(1);
		 PdfPCell cx= new PdfPCell(p9);
		 table4.addCell(cx);
		 /*
         document.add(img);
         document.add(p5);
         document.add(p);
         document.add(p6);
         document.add(p);
         document.add(p);
         document.add(p7);
         document.add(p);
         document.add(p8);
         document.add(p);
         document.add(p7);
         document.add(p);
         document.add(table4);
         
         document.newPage();
         */
         PdfPTable table5 = new PdfPTable(new float[]{1f,1f});
         table5.setWidthPercentage(100);
         PdfPTable tablesx = new PdfPTable(new float[]{1f});
         PdfPTable tabledx = new PdfPTable(new float[]{1f});
         tablesx.setWidthPercentage(100);
         tabledx.setWidthPercentage(100);
         
         
         PdfPCell condpic= new PdfPCell(new PdfPCell(p5));
         PdfPCell spazio= new PdfPCell(new PdfPCell(p));
         PdfPCell att= new PdfPCell(new PdfPCell(p9));
         PdfPCell condgrand= new PdfPCell(new PdfPCell(p6));
         PdfPCell firm= new PdfPCell(new PdfPCell(p7));
         PdfPCell leg= new PdfPCell(new PdfPCell(p8));
         
         condpic.setBorder(0);
         spazio.setBorder(0);
         att.setBorder(0);
         condgrand.setBorder(0);
         firm.setBorder(0);
         leg.setBorder(0);
         
         tablesx.addCell(condpic);
         tablesx.addCell(spazio);
         tablesx.addCell(condgrand);
         tablesx.addCell(spazio);
         tablesx.addCell(firm);
         tablesx.addCell(spazio);
         tablesx.addCell(leg);
         tablesx.addCell(spazio);
         tablesx.addCell(firm);
         tablesx.addCell(spazio);
         tablesx.addCell(att);
         tablesx.addCell(spazio);
         
         tabledx.addCell(img);
         tabledx.addCell(spazio);
         tabledx.addCell(att);
         tabledx.addCell(spazio);
         tabledx.addCell(condpic);
         tabledx.addCell(spazio);
         tabledx.addCell(condgrand);
         tabledx.addCell(spazio);
         tabledx.addCell(leg);
         tabledx.addCell(spazio);
         tabledx.addCell(firm);
         
         
         PdfPCell tabellasx= new PdfPCell(tablesx);
         tabellasx.setBorder(0);
         PdfPCell tabelladx= new PdfPCell(tabledx);
         tabelladx.setBorder(0);
         table5.addCell(tabellasx);
         table5.addCell(tabelladx);
         
         document.add(table5);
         
         document.close();
         Desktop d= Desktop.getDesktop();
         d.open(new File("accettazionetmp.pdf"));
         //new File("accettazionetmp.pdf").delete();
    }
    private static void writePDF(String filename, String destinatario, ArrayList<Riparazione> listaRiparazioni) throws FileNotFoundException, DocumentException, BadElementException, MalformedURLException, IOException {
        GregorianCalendar c = new GregorianCalendar();
        String data = c.get(Calendar.DAY_OF_MONTH) + "/" + c.get(Calendar.MONTH) + 1 + "/" + c.get(Calendar.YEAR);
        String minuto = "" + c.get(Calendar.MINUTE);
        minuto = minuto.length() == 1 ? "0" + minuto : minuto;
        String time = data + "-" + c.get(Calendar.HOUR_OF_DAY) + ":" + minuto;

        int idScheda = new DB().addDocumentoTrasporto(destinatario, time);
        if (idScheda > -1) {
            Document document = new Document(PageSize.A4, 10, 10, 10, 10);
            PdfWriter writer= PdfWriter.getInstance(document,new FileOutputStream(filename));
            
            HeaderFooter event= new HeaderFooter(data,idScheda);
            writer.setPageEvent(event);

            document.open();            
            PdfPTable table2 = new PdfPTable(new float[]{1f, 1f});
            table2.setWidthPercentage(100);
            ParagrafoHeader p1 = new ParagrafoHeader("SPETTABILE");
            ParagrafoHeader p2 = new ParagrafoHeader("MODALITA' DI PAGAMENTO MERCE");
            ParagrafoHeader p3 = new ParagrafoHeader("LUOGO DESTINAZIONE MERCE");
            ParagrafoHeader p4 = new ParagrafoHeader("CAUSALE DEL TRASPORTO");
            ParagrafoHeader p5 = new ParagrafoHeader("CP1 - CONTO RIPARAZIONE");
            
            table2.addCell(new PdfPCell(p1));
            table2.addCell(new PdfPCell(p2));
            table2.addCell(new PdfPCell(new Paragraph(destinatario)));
            PdfPCell cella3 = new PdfPCell(new Paragraph(""));
            cella3.setFixedHeight(70);
            table2.addCell(cella3);
            table2.addCell(new PdfPCell(p3));
            table2.addCell(new PdfPCell(p4));
            table2.addCell(new PdfPCell(new Paragraph(destinatario)));
            PdfPCell cella2 = new PdfPCell(p5);
            cella2.setFixedHeight(70);
            table2.addCell(cella2);
//        		table2.addCell(new PdfPCell(new Paragraph("CP1 - CONTO RIPARAZIONE")));
            // terza tabella
            PdfPTable table3 = new PdfPTable(new float[]{1f, 4f, 1f, 1f});
            table3.setWidthPercentage(100);
            fillTableWithRiparazioni(listaRiparazioni,table3);


            // quarta tabella
            PdfPTable table4 = new PdfPTable(new float[]{2f, 1f, 1f, 1f, 2f, 1f});
            table4.setWidthPercentage(100);
            ParagrafoHeader p6 = new ParagrafoHeader("ASPETTO ESTERIORE DEI BENI");
            ParagrafoHeader p7 = new ParagrafoHeader("N. COLLI");
            ParagrafoHeader p8 = new ParagrafoHeader("TOT. PEZZI");
            ParagrafoHeader p9 = new ParagrafoHeader("PESO KG");
            ParagrafoHeader p10 = new ParagrafoHeader("PORTO");
            ParagrafoHeader p11 = new ParagrafoHeader("DATA E ORA RITIRO");
            Paragraph p12 = new Paragraph("A VISTA");
            Paragraph p13 = new Paragraph("0.00");
            Paragraph p14 = new Paragraph("FRANCO");
            table4.addCell(new PdfPCell(p6));
            table4.addCell(new PdfPCell(p7));
            table4.addCell(new PdfPCell(p8));
            table4.addCell(new PdfPCell(p9));
            table4.addCell(new PdfPCell(p10));
            table4.addCell(new PdfPCell(p11));
            table4.addCell(new PdfPCell(p12));
            table4.addCell(new PdfPCell(new Paragraph(""+listaRiparazioni.size())));
            table4.addCell(new PdfPCell(new Paragraph(""+listaRiparazioni.size())));
            table4.addCell(new PdfPCell(p13));
            table4.addCell(new PdfPCell(p14));
            String[] t = time.split("-");
            table4.addCell(new PdfPCell(new Paragraph(t[0]+"  "+t[1])));
            
            PdfPTable table5 = new PdfPTable(new float[]{4f, 1f});		
            PdfPTable table6 = new PdfPTable(new float[]{3f, 1f});
            creaFooter(table5, table6);
            
            document.add(table2);
            document.add(new Paragraph("\n\n"));
            document.add(table3);
            document.add(table4);
            document.add(new Paragraph("\n"));
            
            document.add(table5);
            document.add(table6);

            document.close();
        }
    }


    public static void print(DestinatarioDT destinatario, ArrayList<Riparazione> listaRiparazioni) {
        File f = new File("print_tmp.pdf");
        if (f.exists()) {
            f.delete();
        }

    }
}
